<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getUsers">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="users" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="220"  sortable>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="150" >
            </el-table-column>
            <el-table-column prop="avatar" label="头像" width="120">
                <template   slot-scope="scope">
                    <img :src="scope.row.avatar" height="40" style="margin-top: 3px" />
                </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别" width="180" :formatter="formatSex" sortable>
            </el-table-column>
            <el-table-column prop="createTimeStr" label="注册时间" width="240" sortable>
            </el-table-column>
            <el-table-column prop="status" label="状态" min-width="80" sortable :formatter="formatStatus" >
            </el-table-column>
            <el-table-column label="操作" width="320">
                <template slot-scope="scope">
                    <el-button type="warning" v-if="scope.row.status==1" size="small" @click="handleState(scope.$index, scope.row)">禁用</el-button>
                    <el-button type="success" v-if="scope.row.status==0" size="small" @click="handleState(scope.$index, scope.row)">启用</el-button>
                    <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                    <el-button type="default" size="small" @click="handlePassword(scope.$index, scope.row)">修改密码</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination      layout="total,prev, pager, next,jumper" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->
        <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="editForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone" >
                    <el-input type="tel" v-model="editForm.phone"  auto-complete="off" ></el-input>
                </el-form-item>
                <el-form-item label="头像：" prop="avatar" >

                    <el-upload
                            action="/admin/user/upload"
                            :on-success="onUploadSuccess"
                            list-type="picture-card"
                    >
                        <i class="el-icon-upload" ></i>
                    </el-upload>

                </el-form-item>
                <el-form-item label="性别" prop="gender" >
                    <el-radio-group v-model="editForm.gender">
                        <el-radio class="radio" :label="1" >男</el-radio>
                        <el-radio class="radio" :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone" >
                    <el-input type="tel" v-model="addForm.phone"  auto-complete="off" ></el-input>
                </el-form-item>
                <el-form-item label="头像：" prop="avatar" >

                    <el-upload
                            action="/admin/user/upload"
                            :on-success="onUploadSuccess"
                            list-type="picture-card"
                    >
                    <i class="el-icon-upload" ></i>
                    </el-upload>

                </el-form-item>
                <el-form-item label="性别" prop="gender" >
                    <el-radio-group v-model="addForm.gender">
                        <el-radio class="radio" :label="1" >男</el-radio>
                        <el-radio class="radio" :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="密码" prop="password" >
                    <el-input type="password" v-model="addForm.password"  auto-complete="off" ></el-input>
                </el-form-item>
                <el-form-item label="密码确认"  prop="rePassword" >
                    <el-input type="password" v-model="addForm.rePassword"  auto-complete="off" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import {validatePhone} from '../../../static/js/validate'
    //import NProgress from 'nprogress'
    import {getUserListPage, removeUser, batchRemoveUser, saveUser} from '../../api/api';

    let validPhone=(rule, value,callback)=>{
        if (!value) {
            callback(new Error('请输入电话号码'))
        }else  if (!validatePhone(value)){
            callback(new Error('请输入正确的11位手机号码'))
        }else {
            callback()
        }
    }



    export default {
        data() {
            let validatePass = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入密码'))
                } else if (value.toString().length < 6 || value.toString().length > 18) {
                    callback(new Error('密码长度为6 - 18个字符'))
                } else {
                    callback()
                }
            }
            let validateRePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== this.addForm.password) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
            return {
                filters: {
                    name: ''
                },
                users: [],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [], //列表选中列
                fileList: [],
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, trigger: 'blur', validator: validPhone  }
                    ]
                },
                //编辑界面数据
                editForm: {
                    id: 0,
                    name: '',
                    avatar: '',
                    gender: -1,
                    phone: ''
                    // password: '',
                    // rePassword: ''
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, trigger: 'blur', validator: validPhone  }
                    ],
                    password:[
                        { required: true, trigger: 'blur', validator: validatePass }
                    ],
                    rePassword: [
                        {required: true, trigger: 'blur', validator: validateRePass }
                    ]
                },
                //新增界面数据
                addForm: {
                    name: '',
                    avatar: '',
                    gender: '1',
                    phone: '',
                    password: '',
                    rePassword: ''
                }

            }
        },
        methods: {
            //性别显示转换
            formatSex: function (row, column) {
                return row.gender == 1 ? '男' : row.gender == 2 ? '女' : '未知';
            },
            formatStatus: function(row,column){
               return   row.status == 1 ? '正常' : row.status == 0 ? '已禁用' : '未知';
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            onUploadSuccess(res,file){
                this.addForm.avatar = res.path
                this.editForm.avatar = res.path
            },
            //获取用户列表
            getUsers() {
                let para = {
                    page: this.page,
                    name: this.filters.name
                };
                this.listLoading = true;
                //NProgress.start();
                getUserListPage(para).then((res) => {
                    let data = res.data.data;
                    this.total = data.totalRow;
                    this.users = data.list;
                    this.listLoading = false;
                    //NProgress.done();
                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { id: row.id };
                    removeUser(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                let user = Object.assign({}, row);
                this.editForm.id = user.id
                this.editForm.name = user.name
                this.editForm.phone = user.phone
                this.editForm.gender = user.gender
                this.editForm.avatar = user.avatar
                console.log(this.editForm)
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    name: '',
                    avatar: '',
                    gender: 1,
                    phone: '',
                    password: '',
                    rePassword: ''
                };
            },
            handleState: function(index,row){
                let question = '确定要禁用该用户吗？'
                let user  ={
                    id: row.id,
                    status: 0
                }
                if(row.status==0){
                    question = '确定要启用该用户吗？'
                    user.status = 1;
                }
                this.$confirm(question, '提示', {}).then(() => {
                    this.editLoading = true;
                    saveUser(user).then((res) => {
                        if(res.code == 200){
                            this.editLoading = false;
                            //NProgress.done();
                            this.$message({
                                message: user.status==0?'已禁用':'已启用',
                                type: 'success'
                            });
                            // this.$refs['editForm'].resetFields();
                            // this.editFormVisible = false;
                            this.getUsers();
                        }
                    });
                })
            },
            handlePassword: function(index,row){

            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);
                            // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            saveUser(para).then((res) => {
                                if(res.code == 200){
                                    this.editLoading = false;
                                    //NProgress.done();
                                    this.$message({
                                        message: '编辑成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();
                                }
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                let _this = this;
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);
                            // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            saveUser(para).then((res) => {
                                if(res.code == 200){
                                    this.addLoading = false;
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['addForm'].resetFields();
                                    this.addFormVisible = false;
                                    this.getUsers();
                                }else{
                                    _this.$message({
                                        type: 'error',
                                        message: res.msg
                                    })
                                }
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { ids: ids };
                    batchRemoveUser(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            this.getUsers();
        }
    }

</script>

<style scoped>

</style>
